package com.thlws.rabbitmq.pubsub;

import com.rabbitmq.client.*;
import com.rabbitmq.client.AMQP.BasicProperties;

import java.util.HashMap;
import java.util.Map;

/***
 * 发布订阅模式
 * BuiltinExchangeType.FANOUT
 * Producer数据都发往Exchange,消费端与Exchange绑定后，多个消费端都可以收到消息.
 * 注意此时 routingKey 为空
 */
public class Producer {

	private static final String EXCHANGE_NAME = "logs";
	
	private static final int DELIVERY_MODE_PERSISTENT = 2;
	private static final int DELIVERY_MODE_NON_PERSISTENT = 1;

	public static void main(String[] args) throws Exception {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("116.228.212.36");
		factory.setUsername("hanley");
		factory.setPassword("hanley");
		factory.setVirtualHost("/test");

		//factory.setAutomaticRecoveryEnabled(true);
		
		try (Connection connection = factory.newConnection();
				Channel channel = connection.createChannel()) {
			
			String message = "发布订阅模式,测试消息.";
			
			Map<String, Object> headers = new HashMap<String, Object>();
			headers.put("latitude",  51.5252949);
			headers.put("longitude", -0.0905493);
			
			AMQP.BasicProperties.Builder build = new AMQP.BasicProperties.Builder();
			BasicProperties basicProperties = build.contentEncoding("UTF-8")
			.deliveryMode(DELIVERY_MODE_PERSISTENT)
			.priority(1)
			.userId("hanley")
			.contentType("text/plain")
			.headers(headers)
			.build();
			
			//BuiltinExchangeType.FANOUT 表示发布订阅模式
			channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
			channel.basicPublish(EXCHANGE_NAME, "", basicProperties, message.getBytes("UTF-8"));
			
			System.out.println(" [x] Sent '" + message + "'");
			
		}
		
	}

}
